﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using mshtml;
using SHDocVw;
using System.Runtime.Serialization.Json;  

namespace EasyCarApp
{
    public partial class Form1 : Form
    {
        private System.Timers.Timer yichewangtimer;
        private string yichewangUserName;
        private string yichewangPassword;
        private System.Timers.Timer qichezhijiatimer;
        private string qichezhijiaUserName;
        private string qichezhijiaPassword;        
        private System.Timers.Timer taipingyangtimer;
        private string taipingyangUserName;
        private string taipingyangPassword;

        private string stateForYCW = "init";
        private int NoProcessOrderNumber = 1;
        private string stateForQCZJ = "init";
        private string stateForTPYQC = "init";

        private const int TIMER_SECONDS = 1000 * 6;

        public Form1()
        {
            InitializeComponent();
            
            (wbYiCheWang.ActiveXInstance as SHDocVw.WebBrowser).NavigateComplete2 += new DWebBrowserEvents2_NavigateComplete2EventHandler(Form1_NavigateComplete2);
            (wbQiCheZhiJia.ActiveXInstance as SHDocVw.WebBrowser).NavigateComplete2+=new DWebBrowserEvents2_NavigateComplete2EventHandler(Form1_NavigateComplete2);
            (wbTaiPingYang.ActiveXInstance as SHDocVw.WebBrowser).NavigateComplete2+=new DWebBrowserEvents2_NavigateComplete2EventHandler(Form1_NavigateComplete2);
             
            yichewangtimer = new System.Timers.Timer();
            qichezhijiatimer = new System.Timers.Timer();
            taipingyangtimer = new System.Timers.Timer();
            this.Load += new EventHandler(Form1_Load);
        }

        void Form1_Load(object sender, EventArgs e)
        {
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
        }


        #region 定时自动处理
        void yichewangtimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            this.wbYiCheWang.Navigate("http://das.bitauto.com/");
            stateForYCW = "init";
        }
        void qichezhijiatimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            this.wbQiCheZhiJia.Navigate("http://dealer.autohome.com.cn/passport/login.aspx");
            stateForQCZJ = "init";
        }
        void taipingyangtimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            this.wbTaiPingYang.Navigate("http://4s.pcauto.com.cn/home/");
            stateForTPYQC = "init";
        }
        #endregion

        #region 打开页面完成事件处理
        void Form1_NavigateComplete2(object pDisp, ref object URL)
        {
            try
            {
                IHTMLDocument2 doc = (wbYiCheWang.ActiveXInstance as SHDocVw.WebBrowser).Document as IHTMLDocument2;
                SetUpDoc(doc);
                doc = (wbQiCheZhiJia.ActiveXInstance as SHDocVw.WebBrowser).Document as IHTMLDocument2;
                SetUpDoc(doc);
                doc = (wbTaiPingYang.ActiveXInstance as SHDocVw.WebBrowser).Document as IHTMLDocument2;
                SetUpDoc(doc);
            }
            catch { }
        }
        void SetUpDoc(IHTMLDocument2 doc)
        {
            try
            {
                doc.parentWindow.execScript("window.alert=null", "javascript");
                doc.parentWindow.execScript("window.confirm=null", "javascript");
                doc.parentWindow.execScript("window.open=null", "javascript");
                doc.parentWindow.execScript("window.showModalDialog=null", "javascript");
                doc.parentWindow.execScript("window.close=null", "javascript");
            }
            catch
            { }
        }
        #endregion

        #region 易车网
        private void wbYiCheWang_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            try
            {
                if (this.yichewangUserName == null)
                { return; }
                HtmlDocument doc = this.wbYiCheWang.Document;
                switch (stateForYCW)
                {
                    case "init"://输入密码并登录 
                        WriteLog(this.lbYiche, "登陆验证..");
                        doc.GetElementById("txtUserName").InnerText = this.yichewangUserName;
                        doc.GetElementById("txtPassword").InnerText = this.yichewangPassword;
                        doc.GetElementById("btnLogin").InvokeMember("click");
                        stateForYCW = "logined";
                        break;
                    case "logined"://切换到刷新报价页面
                        WriteLog(this.lbYiche, "验证通过");
                        this.wbYiCheWang.Navigate("http://das.bitauto.com/Price/PriceManage.aspx");
                        stateForYCW = "refrushprice";
                        break;
                    case "refrushprice"://刷新报价
                        WriteLog(this.lbYiche, "刷新报价..");
                        doc.GetElementById("btnUpdateBatch").InvokeMember("click");//有已经是最新报价的警告
                        stateForYCW = "refrushpriced";
                        break;
                    case "refrushpriced":
                        WriteLog(this.lbYiche, "报价刷新完毕");
                        this.wbYiCheWang.Navigate("http://das.bitauto.com/InforManage/News/NewsList.aspx");
                        stateForYCW = "pushnews";
                        break;
                    case "pushnews":
                        WriteLog(this.lbYiche, "推送新闻..");
                        doc.GetElementById("dgvNewsList_ctl02_lbtnRecommand").InvokeMember("click");//可能会有限制10次的警告
                        stateForYCW = "startorder";
                        break;
                    case "startorder"://查看新车订单
                        WriteLog(this.lbYiche, "新闻推送完毕");
                        wbYiCheWang.Navigate("http://das.bitauto.com/CRM/NewCarBusinessOpportunity.aspx");
                        stateForYCW = "allorder";
                        break;
                    case "allorder"://定位到未处理订单，点击处理
                        WriteLog(this.lbYiche, "处理新订单");
                        var number = doc.GetElementById("lbtnNoDeal").InnerText.Substring(4, 1);
                        if (int.Parse(number) == 0)
                        {
                            stateForYCW = "noorder";
                        }
                        else
                        {
                            WriteLog(this.lbYiche, "发现" + int.Parse(number) + "个新订单");
                            HtmlElement table = doc.GetElementById("grvNewCarOpportunity");
                            for (int i = 1; i < 16; i++)
                            {
                                if (table.Children[1].Children[i].Children[1].InnerText == "未处理")
                                {
                                    WriteLog(this.lbYiche, "正在处理" + table.Children[1].Children[i].Children[0].InnerText + "");
                                    var id = table.Children[1].Children[i].Children[0].InnerText;
                                    wbYiCheWang.Navigate("http://das.bitauto.com/CRM/NewCarBusinessOpportunityOperate.aspx?OpportunityID=" + id + "&OperationID=");
                                    stateForYCW = "openprocess";
                                    NoProcessOrderNumber = i;
                                    break;
                                }
                            }
                            //WriteLog(this.lbYiche, "订单处理完毕");
                        }
                        break;
                    case "openprocess":
                        HtmlElement table1 = doc.GetElementById("grvNewCarOpportunity");
                        var id1 = table1.Children[1].Children[NoProcessOrderNumber].Children[0].InnerText;
                        wbYiCheWang.Navigate("http://das.bitauto.com/CRM/NewCarBusinessOpportunityOperate.aspx?OpportunityID=" + id1 + "&OperationID=");
                        stateForYCW = "openprocess1";
                        WriteLog(this.lbYiche, "订单" + table1.Children[1].Children[NoProcessOrderNumber].Children[0].InnerText + "处理完毕");
                        break;
                    case "openprocess1":
                        if (doc.GetElementById("btnSave") != null)
                        {
                            doc.GetElementById("btnSave").InvokeMember("click");
                            stateForYCW = "processed";
                        }
                        if (doc.GetElementById("btnSaveWithSelectMutiCustomer") != null)
                        {
                            doc.GetElementById("btnSaveWithSelectMutiCustomer").InvokeMember("click");
                            stateForYCW = "processed";
                        }
                        break;
                    case "processed":
                        if (doc.Body.InnerHtml.Contains("?OpportunityID="))
                        {
                            stateForYCW = "startorder";
                        }
                        break;
                    case "noorder":
                        WriteLog(this.lbYiche, "整体处理完毕");
                        //this.wbYiCheWang.Navigate("http://www.baidu.com");
                        stateForYCW = "ok";
                        break;
                }
                var count = int.Parse(this.lblYiCheCount.Text);
                this.lblYiCheCount.Text = (count + 1).ToString();
            }
            catch(Exception ex)
            {
                WriteLog(this.lbYiche,"发生错误"+ex.Message);
            }
        }
        #endregion

        #region 汽车之家
        private void wbQiCheZhiJia_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            try
            {
                if (this.qichezhijiaUserName == null)
                { return; }
                HtmlDocument doc = this.wbQiCheZhiJia.Document;
                switch (stateForQCZJ)
                {
                    case "init"://输入密码并登录
                        WriteLog(lbQiCheZhijia, "登录验证..");
                        doc.GetElementById("txtname").InnerText = this.qichezhijiaUserName;
                        doc.GetElementById("txtpwd").InnerText = this.qichezhijiaPassword;
                        doc.GetElementById("sub").InvokeMember("click");
                        stateForQCZJ = "logined";
                        break;
                    case "logined"://切换到刷新报价页面
                        //WriteLog(lbQiCheZhijia, "验证通过");
                        doc.GetElementById("txtname").InnerText = this.qichezhijiaUserName;
                        doc.GetElementById("txtpwd").InnerText = this.qichezhijiaPassword;
                        doc.GetElementById("sub").InvokeMember("click");
                        stateForQCZJ = "loginok";
                        break;
                    case "loginok":
                        WriteLog(lbQiCheZhijia, "验证通过");
                        
                        this.wbQiCheZhiJia.Navigate("http://dealer.autohome.com.cn/Flatcenter/CarPrice.aspx");
                        stateForQCZJ = "refrushprice";
                        break;
                    case "refrushprice"://刷新报价
                        WriteLog(lbQiCheZhijia, "刷新报价..");
                        if (this.wbQiCheZhiJia.Url.AbsoluteUri == "http://dealer.autohome.com.cn/Flatcenter/CarPrice.aspx")
                        {
                            WriteLog(lbQiCheZhijia, "完成刷新报价");
                            doc.GetElementById("btnBatchUpdatePrice").InvokeMember("click");//有已经是最新报价的警告
                        }
                        stateForQCZJ = "refrushpriced";
                        break;
                    case "refrushpriced":
                        WriteLog(lbQiCheZhijia, "开始推送新闻..");
                        this.wbQiCheZhiJia.Navigate("http://dealer.autohome.com.cn/Flatcenter/NewsList.aspx");//推送新闻
                        stateForQCZJ = "pushnews";
                        break;
                    case "pushnews":
                        var index = doc.Body.InnerHtml.IndexOf(";newsid=");
                        if (index != -1)
                        {
                            var str = doc.Body.InnerHtml.Substring(index + 8, 6);
                            this.wbQiCheZhiJia.Navigate("http://dealer.autohome.com.cn/Flatcenter/NewsList.aspx?action=Refresh&newsid=" + str);//可能会有限制10次的警告
                        }
                        stateForQCZJ = "startorder";
                        WriteLog(lbQiCheZhijia, "新闻推送完毕");
                        break;
                    case "startorder"://查看新车订单
                        WriteLog(lbQiCheZhijia, "开始处理新车订单");
                        this.wbQiCheZhiJia.Navigate("http://dealer.autohome.com.cn/Flatcenter/Orders/Unprocessed.aspx");
                        stateForQCZJ = "allorder";
                        break;
                    case "allorder"://查看新车订单
                        this.wbQiCheZhiJia.Navigate("http://dealer.autohome.com.cn/Flatcenter/Orders/Unprocessed.aspx");
                        stateForQCZJ = "allorder1";
                        break;
                    case "allorder1"://定位到未处理订单，点击处理
                        if (!doc.Body.InnerText.Contains("未处理(0)"))
                        {
                            HtmlElementCollection hec = doc.GetElementsByTagName("table");
                            var number = doc.Body.InnerHtml.IndexOf(">查看电话");
                            if (number == -1)
                            {
                                WriteLog(lbQiCheZhijia, "没有订单需要处理");
                                stateForQCZJ = "noorder";
                            }
                            else
                            {

                                HtmlElement table = hec[2];
                                WriteLog(lbQiCheZhijia, "新车订单共有" + table.Children.Count + "个");
                                for (int i = 0; i < table.Children.Count; i++)
                                {
                                    var str = table.Children[i].Children[1].Children[6].InnerHtml;
                                    int start = str.IndexOf("(");
                                    int end = str.IndexOf(")");
                                    str = str.Substring(start + 1, end - start - 1);
                                    doc.GetElementById("spanphone" + str).InvokeMember("click");
                                }
                                stateForQCZJ = "allorder1";
                            }
                        }
                        break;
                    case "noorder"://试驾信息
                        WriteLog(lbQiCheZhijia, "开始处理试驾信息");
                        this.wbQiCheZhiJia.Navigate("http://dealer.autohome.com.cn/FlatCenter/OrderTestDriveManage.aspx?isOrder=2&type=0");
                        stateForQCZJ = "getdriver";
                        break;
                    case "getdriver":
                        var number1 = doc.Body.InnerHtml.IndexOf(">查看电话");
                        if (number1 == -1)
                        {
                            WriteLog(lbQiCheZhijia, "没有试驾信息需要处理");
                            stateForQCZJ = "nodriver";
                        }
                        else
                        {

                            HtmlElement table = doc.GetElementById("tblOrder");
                            WriteLog(lbQiCheZhijia, "共有" + table.Children.Count + "个试驾信息需要处理");
                            //string strMsg=table.Children[0].Children[1].Children[1].InnerText;//试驾人信息
                            doc.GetElementById("ctl00_body_rpt_ctl00_lbOperate").InvokeMember("click");
                            stateForQCZJ = "getdriver";
                        }
                        break;
                    case "nodriver":
                        WriteLog(lbQiCheZhijia, "本次自动处理结束");
                        //this.wbQiCheZhiJia.Navigate("http://www.baidu.com");
                        stateForQCZJ = "end";
                        break;
                }
                var count = int.Parse(this.lblQiCheCount.Text);
                this.lblQiCheCount.Text = (count + 1).ToString();
            }
            catch(Exception ex)
            {
                WriteLog(this.lbQiCheZhijia,"发生错误"+ex.Message);
            }
        }

        #endregion

        #region 太平洋汽车
        /// <summary>
　　      /// JSON反序列化
　　      /// </summary>
　　      public static T JsonDeserialize<T>(string jsonString)
　　      {
            jsonString = jsonString.Replace("\n", "");
　　          DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
　　          MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
　　          T obj = (T)ser.ReadObject(ms);
　　          return obj;
　　       }
        public class Bills
        {
            public int total { set; get; }
            public int pageNo { set; get; }
            public int pageSize { set; get; }
            public Bill[] rows { set; get; }
        }
        public class Bill
        {
            public string createTime { get; set; }
            public string dealerId { get; set; }
            public string phone { get; set; }
            public string isTestDrive { get; set; }
            public string updateTime { get; set; }
            public string status { get; set; }
            public string serialGroupId { get; set; }
            public string _buyTime_desc { get; set; }
            public string version { get; set; }
            public string id { get; set; }
            public string modelId { get; set; }
            public string payMode { get; set; }
            public string buyTime { get; set; }
            public string name { get; set; }
            public string gender { get; set; }
            public string _status_desc { get; set; }
            public string _modelId_name { get; set; }
            public string _rs_ { get; set; }
        }
        private void wbTaiPingYang_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            ProcessTaiPingYang();            
        }
        void ProcessTaiPingYang()
        {
            try
            {
                if (this.taipingyangPassword == null)
                {
                    return;
                }
                string data = "username="+Common.Helper.CodeStr(this.taipingyangUserName)+"&password=" + this.taipingyangPassword + "";
                string url = "http://4s.pcauto.com.cn/dealer/admin/do_login.jsp?_charset=GBK";
                string loginTip = Common.Helper.PostDataToServer(data, url);//登录
                if (!loginTip.Contains("密码不正确"))
                {
                    WriteLog(this.lbTaiPingYang, "登录成功！");
                }
                else
                {
                    WriteLog(this.lbTaiPingYang, "登录失败！");
                    return;
                }
                data = "method=updateAll&manufacturerIds=;107;";
                url = "http://4s.pcauto.com.cn/dealer/admin/action/do_model.jsp";
                string strRefresh = Common.Helper.PostDataToServer(data, url);//刷新报价
                WriteLog(this.lbTaiPingYang, "刷新报价！");
                data = "";
                url = "http://4s.pcauto.com.cn/dealer/admin/action/do_namelist.jsp?method=&pageNo=1&q_ge_createTime=&q_le_createTime=&q_eq_id=&type=0&q_eq_status=0&q_like_name=&q_like_phone=&%E6%9F%A5%E8%AF%A2=&_isajax=true";
                string returnString = Common.Helper.PostDataToServer(data, url);//订单                
                Bills t = JsonDeserialize<Bills>(returnString);
                if (t.rows.Length > 0)
                {
                    WriteLog(this.lbTaiPingYang, "开始处理订单");
                    for (int i = 0; i < t.rows.Length; i++)
                    {
                        data = "method=modify&id=" + t.rows[i].id + "&domainName=DealerOrder&status=1&dMemo=&_isajax=true";
                        url = "http://4s.pcauto.com.cn/dealer/admin/action/do_namelist.jsp";
                        Common.Helper.PostDataToServer(data, url);
                        Common.Helper.SentMsg("在线订车："+t.rows[i].name + "," + t.rows[i].gender + ",手机：" + t.rows[i].phone + "," + t.rows[i]._modelId_name +"--太平洋汽车网");
                        WriteLog(this.lbTaiPingYang, "处理订单[" + t.rows[i].id+"]");
                    }
                    WriteLog(this.lbTaiPingYang, "订单处理完毕");
                }
                else
                {
                    WriteLog(this.lbTaiPingYang, "未发现新订单");
                }
                
                data = "";
                url = "http://4s.pcauto.com.cn/dealer/admin/action/do_namelist.jsp?method=&pageNo=1&q_ge_createTime=&q_le_createTime=&q_eq_id=&type=1&q_eq_status=0&q_like_name=&q_like_phone=&%E6%9F%A5%E8%AF%A2=&_isajax=true";
                returnString = Common.Helper.PostDataToServer(data, url);//试驾
                
                t = JsonDeserialize<Bills>(returnString);
                if (t.rows.Length > 0)
                {
                    WriteLog(this.lbTaiPingYang, "开始处理试驾信息");
                    for (int i = 0; i < t.rows.Length; i++)
                    {
                        data = "method=modify&id=" + t.rows[i].id + "&domainName=DealerDrive&status=1&dMemo=&_isajax=true";
                        url = "http://4s.pcauto.com.cn/dealer/admin/action/do_namelist.jsp";
                        Common.Helper.PostDataToServer(data, url);
                        Common.Helper.SentMsg("赏车试驾：" + t.rows[i].name + "," + t.rows[i].gender + ",手机：" + t.rows[i].phone + "," + t.rows[i]._modelId_name + "--太平洋汽车网");
                        WriteLog(this.lbTaiPingYang, "处理试驾" + t.rows[i].id);
                    }
                    WriteLog(this.lbTaiPingYang, "试驾信息处理完毕");
                }
                else
                {
                    WriteLog(this.lbTaiPingYang, "未发现新试驾信息");
                }
                var count = int.Parse(this.lblTaiPingYangCount.Text);
                this.lblTaiPingYangCount.Text = (count + 1).ToString();
            }
            catch(Exception ex)
            {
                WriteLog(this.lbTaiPingYang, "错误"+ex.Message);
            }
        }
        #endregion

        void WriteLog(ListBox listBox, string content)
        { 
                listBox.Items.Insert(0, DateTime.Now.ToString("HH:mm:ss:") + content);
        }

        private void btnYicheStart_Click(object sender, EventArgs e)
        {       
            if(this.txtYicheUserName.Text!=""&&this.txtYichePassword.Text!="")
            {
                this.yichewangUserName = this.txtYicheUserName.Text;
                this.yichewangPassword = this.txtYichePassword.Text;
                yichewangtimer.Interval = TIMER_SECONDS;
                yichewangtimer.Elapsed += new System.Timers.ElapsedEventHandler(yichewangtimer_Elapsed);
                this.yichewangtimer.Start();
                this.btnYicheStart.Enabled = false;
                this.btnYicheStop.Enabled = true;
            }            
        }
        private void btnYicheStop_Click(object sender, EventArgs e)
        {
            this.yichewangtimer.Stop();
            this.btnYicheStart.Enabled = true;
            this.btnYicheStop.Enabled = false;
        }

        private void btnQicheStart_Click(object sender, EventArgs e)
        {
            if (this.txtQicheUserName.Text != "" && this.txtQichePassword.Text != "")
            {
                this.qichezhijiaUserName = this.txtQicheUserName.Text;
                this.qichezhijiaPassword = this.txtQichePassword.Text;
                qichezhijiatimer.Interval = TIMER_SECONDS;
                qichezhijiatimer.Elapsed += new System.Timers.ElapsedEventHandler(qichezhijiatimer_Elapsed);
                this.qichezhijiatimer.Start();
                this.btnQicheStart.Enabled = false;
                this.btnQicheStop.Enabled = true;
            }
        }
        private void btnQicheStop_Click(object sender, EventArgs e)
        {
            this.qichezhijiatimer.Stop();
            this.btnQicheStart.Enabled = true;
            this.btnQicheStop.Enabled = false;
        }

        private void btnTPYStart_Click(object sender, EventArgs e)
        {
            if (this.txtTPYPassword.Text != "")
            {
                this.taipingyangUserName = this.txtTPYUserName.Text;
                this.taipingyangPassword = this.txtTPYPassword.Text;
                taipingyangtimer.Interval = TIMER_SECONDS;
                taipingyangtimer.Elapsed += new System.Timers.ElapsedEventHandler(taipingyangtimer_Elapsed);
                this.taipingyangtimer.Start();
            }
            else
            {
                MessageBox.Show("请输入密码！");
            }

            this.btnTPYStart.Enabled = false;
            this.btnTPYStop.Enabled = true;
        }
        private void btnTPYStop_Click(object sender, EventArgs e)
        {
            this.taipingyangtimer.Stop();
            this.btnTPYStart.Enabled = true;
            this.btnTPYStop.Enabled = false;
        }


    }
}
